import { GraphicsGroupItem } from "@/config/graphicsGroup.ts";
import { Collapse } from "antd";
import { FolderOutlined, LoadingOutlined } from "@ant-design/icons";
import styles from "@/layout/Graphics/Graphics.module.scss";
import React, { useState } from "react";
import axios from "@/utils/request.ts";
import localforage from "localforage";
import { deepClone, Pen } from "@meta2d/core";
function InterceptKey(txt: string) {
  if (txt.length <= 15) {
    return txt;
  }
  return txt.slice(0, 15) + "...";
}

function SvgCom({
  item,
  countMap,
}: {
  item: GraphicsGroupItem;
  countMap: { [key: string]: number };
}) {
  const [loading, setLoading] = useState<boolean>(false);
  const [list, setList] = useState<any[]>([]);
  const requestList = function () {
    setLoading(true);
    return new Promise((resolve, reject) => {
      if (item.api != null) {
        axios
          .get(item.api + item.key + ".json")
          .then((r) => {
            resolve(r.data);
          })
          .catch(() => {
            resolve([]);
          })
          .finally(() => {
            setLoading(false);
          });
      } else {
        reject([]);
      }
    });
  };
  const dragStart = (
    e: React.MouseEvent<HTMLDivElement>,
    elem: any,
    url: string,
  ) => {
    if (!elem) {
      return;
    }
    e.stopPropagation();
    let pens: Pen[] = [];
    const addData = () => {
      if (e instanceof DragEvent) {
        // 设置拖拽数据
        e.dataTransfer?.setData("Meta2d", JSON.stringify(pens));
      } else {
        // 支持单击添加图元。平板模式
        window.meta2d.canvas.addCaches = deepClone(pens);
      }
    };
    // 创建对象
    const img = new Image();
    // 改变图片的src
    img.src = url;
    img.onload = function () {
      if (url.includes(".gif")) {
        pens = [
          {
            width: img.width,
            height: img.height,
            name: "gif",
            image: url,
            ratio: true,
          },
        ];
      } else {
        pens = [
          {
            width: img.width,
            height: img.height,
            name: "image",
            image: url,
            ratio: true,
          },
        ];
      }
      addData();
    };
  };

  const handleCollapseOpen = () => {
    localforage.getItem(item.key).then((value) => {
      if (value != null) {
        setList(() => value as any[]);
      } else {
        requestList().then((data) => {
          setList(() => data as any[]);
          localforage.setItem(item.key, data);
        });
      }
    });
  };
  return (
    <>
      <Collapse
        style={{ border: "none", borderRadius: 0, borderColor: "#000000" }}
        expandIconPosition={"end"}
        key={encodeURIComponent(item.key)}
        onChange={handleCollapseOpen}
        items={[
          {
            key: "panel",
            label: (
              <>
                {loading ? (
                  <LoadingOutlined style={{ marginRight: 5 }} />
                ) : (
                  <FolderOutlined style={{ marginRight: 5 }} />
                )}
                <span title={item.key}>{InterceptKey(item.key)}</span>(
                {countMap[item.key] || "0"})
              </>
            ),
            children: (
              <div className={styles.GraphicsItem}>
                {list.map((_listItem) => {
                  return (
                    <div
                      draggable={true}
                      key={_listItem.name}
                      title={_listItem.name}
                      className="item"
                      onDragStart={(event) =>
                        dragStart(event, _listItem, item.api + _listItem.name)
                      }
                      onClick={(event) =>
                        dragStart(event, _listItem, item.api + _listItem.name)
                      }
                    >
                      {item.api && (
                        <img
                          src={item.api + _listItem.name}
                          alt="_listItem.name"
                        />
                      )}
                    </div>
                  );
                })}
              </div>
            ),
            style: {
              borderRadius: 0,
            },
          },
        ]}
        defaultActiveKey={[]}
      ></Collapse>
    </>
  );
}
export default React.memo(SvgCom);
